package com.example.jksj.bookmanagement.pro.mine.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.InputType;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.jksj.bookmanagement.R;
import com.example.jksj.bookmanagement.event.MessageEvent;
import com.example.jksj.bookmanagement.event.StudengInfoEvent;
import com.example.jksj.bookmanagement.common.MyActivity;
import com.example.jksj.bookmanagement.utils.L;
import com.example.jksj.bookmanagement.utils.ShareUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

public class UserManageActivity extends MyActivity implements View.OnClickListener {

    private RelativeLayout photoBtn;        //选择头像按钮
    private RelativeLayout nameBtn;         //姓名按钮
    private RelativeLayout genderBtn;       //性别按钮
    private RelativeLayout describeBtn;     //描述按钮
    private RelativeLayout phoneNumberBtn;  //手机号按钮
    private RelativeLayout schoolBtn;       //学校选择按钮

    private CircleImageView photoIV;              //显示头像
    private TextView nameTV;                //显示姓名
    private TextView genderTV;              //显示性别
    private TextView describeTV;            //显示描述
    private TextView phoneNumberTV;         //显示手机号
    private TextView schoolTV;              //显示学校
    private TextView studentIDTV;           //显示学生学号

    private static final int IMAGE = 1;
    private String imagePath;

    int checkedIndex = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_user_manage;
    }

    @Override
    protected int getTitleBarId() {
        return R.id.tb_userManage_title;
    }

    @Override
    protected void initView() {
        photoBtn = findViewById(R.id.rl_photo_userManage);
        photoBtn.setOnClickListener(this);

        nameBtn = findViewById(R.id.rl_name_userManage);
        nameBtn.setOnClickListener(this);

        genderBtn = findViewById(R.id.rl_gender_userManage);
        genderBtn.setOnClickListener(this);

        describeBtn = findViewById(R.id.rl_describe_Manage);
        describeBtn.setOnClickListener(this);

        phoneNumberBtn = findViewById(R.id.rl_phone_Manage);
        phoneNumberBtn.setOnClickListener(this);

        schoolBtn = findViewById(R.id.rl_school_Manage);
        schoolBtn.setOnClickListener(this);

        photoIV = findViewById(R.id.iv_phone_userManage);
        nameTV = findViewById(R.id.tv_name_userManage);
        genderTV = findViewById(R.id.tv_gender_userManage);
        describeTV = findViewById(R.id.tv_describe_userManage);
        phoneNumberTV = findViewById(R.id.tv_phoneNumber_userManage);
        schoolTV = findViewById(R.id.tv_school_userManage);
        studentIDTV = findViewById(R.id.tv_studentID_userManage);
    }

    @Override
    protected void initData() {

        //进行EventBus注册
        EventBus.getDefault().register(this);

        //缓存本地头像
        String imaePath = ShareUtils.getString("title_Image", "");
        if (!imaePath.equals("")){
            File file = new File(imaePath);
            Glide.with(this).load(file).into(photoIV);
            //L.i(imaePath);
        }

        boolean isAuthentication = ShareUtils.getBoolean("StudentInfo", false);
        if (isAuthentication){
            //缓存实名认证信息
            schoolTV.setText(ShareUtils.getString("StudengInfo_shcool", ""));
            studentIDTV.setText(ShareUtils.getString("StudengInfo_studentID", ""));
            nameTV.setText(ShareUtils.getString("StudengInfo_name", ""));
            genderTV.setText(ShareUtils.getString("StudengInfo_gender", ""));
            phoneNumberTV.setText(ShareUtils.getString("StudengInfo_studentPhone", ""));
        }else {
            //弹出提示信息
            TipDialog();
        }
    }

    //提示用户去实名认证
    private void TipDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("请先去实名认证")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                       startActivity(AuthenticationActivity.class);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_photo_userManage:
                //底部弹出按钮
                BottomSheetList();
                break;

            case R.id.rl_describe_Manage:
                Edit("个人描述", "在此输入您的描述信息", "请输入描述信息", describeTV, false);
                break;

            case R.id.rl_phone_Manage:
                Edit("手机号码", "在此输入您的手机号码", "请输入正确的号码", phoneNumberTV, true);
                break;

            case R.id.rl_school_Manage:
                startActivity(AuthenticationActivity.class);
                break;
        }
    }



    //弹出性别选择对话框
    private void SelectGender() {
        final String[] items = new String[]{"男", "女"};
        new QMUIDialog.CheckableDialogBuilder(this)
                .setCheckedIndex(checkedIndex)
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        genderTV.setText(items[which]);
                        checkedIndex = which;
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    //弹出输入对话框
    private void Edit(String Title, String Placeholder, final String Toast, final View view, final boolean isPhone) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle(Title)
                .setPlaceholder(Placeholder)
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            ((TextView)view).setText(text);
                            if (isPhone){
                                ShareUtils.putString("StudengInfo_studentPhone", text.toString());
                            }
                            dialog.dismiss();
                        } else {
                           toast(Toast);
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }
    //底部弹窗
    private void BottomSheetList(){
        new QMUIBottomSheet.BottomListSheetBuilder(getActivity())
                .addItem("从相册选择图片")
                .addItem("拍照")
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        switch (position){
                            case 0:
                                //调用相册
                                Intent intent = new Intent(Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent, IMAGE);
                                break;

                            case 1:

                                break;
                        }
                    }
                })
                .build()
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getActivity().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            imagePath = c.getString(columnIndex);
            //加载图片
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            photoIV.setImageBitmap(bm);
            ShareUtils.putString("title_Image", imagePath);
            c.close();
        }
    }

    /**
     * 界面销毁时向MineFragment发送一个图片地址
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new MessageEvent(imagePath));
    }

    //用于接收EventBus
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(StudengInfoEvent studengInfoEvent) {
        schoolTV.setText(studengInfoEvent.getSchoolID());
        studentIDTV.setText(studengInfoEvent.getStudentID());
        nameTV.setText(studengInfoEvent.getStudentName());
        genderTV.setText(studengInfoEvent.getStudentGender());
       L.d(studengInfoEvent.toString());
    }
}
